package com.llxwz.controller;


import com.llxwz.entity.Event;
import com.llxwz.entity.User;
import com.llxwz.event.EventProducer;
import com.llxwz.service.LikeService;
import com.llxwz.util.CommunityConstant;
import com.llxwz.util.CommunityUtil;
import com.llxwz.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;



    @PostMapping("/like")
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId,int postId) {
        User user = hostHolder.getUser();

        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);

        // 某实体被点赞的数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 状态  某人对某实体的点赞状态（已赞或未赞）
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        // 返回的结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        // 触发点赞事件
        if (likeStatus == 1) {//只有点赞的时候再发送消息
            Map<String,Object> m = new HashMap<>();
            m.put("postId", postId);
            Event event = new Event().builder()
                    .exchangeName(EXCHANGE_NAME)
                    .queueName(QUEUE_LIKE)
                    .routeName(ROUTE_LIKE)
                    .userId(hostHolder.getUser().getId())
                    .entityType(entityType)
                    .entityId(entityId)
                    .entityUserId(entityUserId)
                    .data(m)
                    .build();
            eventProducer.fireEvent(event);
        }


        /*if(entityType == ENTITY_TYPE_POST) {
            // 计算帖子分数
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);
        }*/

        return CommunityUtil.getJsonString(0, null, map);
    }

}
